<?php

namespace app\shop\controller;

use think\Controller;

class Order extends Controller
{
  public function __construct()
  {
    parent::__construct();

    $this->ProductModel = model('Product.Product');
    $this->CartModel = model('Product.Cart');
    $this->BusinessModel = model('Business.Business');
    $this->AddressModel = model('Business.Address');
    $this->OrderModel = model('Order.Order');
    $this->OrderProductModel = model('Order.Product');
    $this->RecordModel = model('Business.Record');
    $this->DepotModel = model('Depot.back.Back');
    $this->DepotProductModel = model('Depot.back.Product');

    $busid = $this->request->param('busid', 0, 'trim');

    $this->business = $this->BusinessModel->find($busid);

    if (!$this->business) {
      $this->error('用户不存在');
      exit;
    }
  }

  // 列表
  public function index()
  {
    if ($this->request->isPost()) {
      $page = $this->request->param('page', 1, 'trim');
      $status = $this->request->param('status', 0, 'trim');
      $limit = 8;

      //偏移量
      $offset = ($page - 1) * $limit;

      $where = ['busid' => $this->business['id']];

      if ($status != 0) {
        $where['status'] = $status;
      }

      $list = $this->OrderModel
        ->where($where)
        ->order('id', 'desc')
        ->limit($offset, $limit)
        ->select();


      // 继续查询订单商品表（因为需要通过订单商品表来关联到商品表）
      if ($list) {
        foreach ($list as $item) {
          // 查询出订单商品表去进行链表到--商品表
          $info = $this->OrderProductModel->with(['products'])->where(['orderid' => $item['id']])->find();

          // 将商品表中的名字和图片拿到
          $proname = isset($info['products']['name']) ? $info['products']['name'] : '';
          $thumbs_cdn = isset($info['products']['thumbs_cdn']) ? $info['products']['thumbs_cdn'] : '';

          // 再赋值到list里面去
          $item['proname'] = $proname;
          $item['thumbs_cdn'] = $thumbs_cdn;
        }
      }

      // var_dump(collection($list)->toArray());
      // exit;

      if ($list) {
        $this->success('返回订单数据', null, $list);
        exit;
      } else {
        $this->error('暂无更多订单数据');
        exit;
      }
    }
  }

  // 下单
  /**
   * 涉及表：
   *    订单表 
   *    订单商品表  
   *    商品表  
   *    用户余额表 
   *    消费记录表 
   *    购物车表
   */
  public function add()
  {
    if ($this->request->isPost()) {
      $busid = $this->request->param('busid', 0, 'trim');
      $cartids = $this->request->param('cartids', 0, 'trim');
      $addrid = $this->request->param('addrid', 0, 'trim');
      $remark = $this->request->param('remark', '', 'trim');

      //先判断用户是否存在
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      //判断是否有购物车记录
      $cart = $this->CartModel->with(['product'])->where(['cart.id' => ['in', $cartids]])->select();

      // var_dump(collection($cart)->toArray());
      // exit;

      if (!$cart) {
        $this->error('购物车记录不存在');
        exit;
      }

      $where = [
        'busid' => $busid,
        'id' => $addrid
      ];

      $address = $this->AddressModel->where($where)->find();

      if (!$address) {
        $this->error('收货地址不存在');
        exit;
      }

      //判断商品的库存是否充足
      foreach ($cart as $item) {
        // 商品库存
        $stock = isset($item['product']['stock']) ? $item['product']['stock'] : 0;
        $proname = isset($item['product']['name']) ? $item['product']['name'] : '';

        if ($item['nums'] > $stock) {
          $this->error("$proname 商品库存不足");
          exit;
        }
      }

      //先判断余额是否充足
      $total = $this->CartModel->where(['id' => ['in', $cartids]])->sum('total');

      $UpdateMoney = bcsub($business['money'], $total);

      if ($UpdateMoney < 0) {
        $this->error('余额不足');
        exit;
      }

      //开启事务
      $this->OrderModel->startTrans();
      $this->OrderProductModel->startTrans();
      $this->ProductModel->startTrans();
      $this->BusinessModel->startTrans();
      $this->RecordModel->startTrans();
      $this->CartModel->startTrans();


      //订单表
      $OrderData = [
        'code' => build_code("FA"),
        'busid' => $busid,
        'businessaddrid' => $addrid,
        'amount' => $total,
        'remark' => $remark,
        'status' => '1',
      ];

      $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);

      if ($OrderStatus === FALSE) {
        $this->error($this->OrderModel->getError());
        exit;
      }

      //订单商品表
      $OrderProductData = [];
      $ProductData = [];

      foreach ($cart as $item) {
        $OrderProductData[] = [
          'orderid' => $this->OrderModel->id,
          'proid' => $item['proid'],
          'pronum' => $item['nums'],
          'price' => $item['price'],
          'total' => $item['total'],
        ];

        //更新商品的库存
        $stock = isset($item['product']['stock']) ? $item['product']['stock'] : 0;

        //更新后的库存
        $UpdateStock = bcsub($stock, $item['nums']);
        $UpdateStock = $UpdateStock <= 0 ? 0 : $UpdateStock;

        //组装数据
        $ProductData[] = [
          'id' => $item['proid'],
          'stock' => $UpdateStock
        ];
      }

      $OrderProductStatus = $this->OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

      if ($OrderProductStatus === FALSE) {
        $this->OrderModel->rollback();
        $this->error($this->OrderProductModel->getError());
        exit;
      }

      //更新商品库存
      $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

      if ($ProductStatus === FALSE) {
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->ProductModel->getError());
        exit;
      }

      //用户表更新余额
      $BusinessData = [
        'id' => $busid,
        'money' => $UpdateMoney
      ];

      $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

      if ($BusinessStatus === FALSE) {
        $this->ProductModel->rollback();
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->BusinessModel->getError());
        exit;
      }

      //消费记录
      $RecordData = [
        'total' => "-$total",
        'content' => "购物商品花费余额为：￥$total 元",
        'busid' => $busid
      ];

      $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

      if ($RecordStatus === FALSE) {
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->RecordModel->getError());
        exit;
      }

      //购物车表执行删除语句
      $CartStatus = $this->CartModel->where(['id' => ['in', $cartids]])->delete();

      if ($CartStatus === FALSE) {
        $this->RecordModel->rollback();
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error($this->CartModel->getError());
        exit;
      }

      if ($OrderStatus === FALSE || $OrderProductStatus === FALSE || $ProductStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE || $CartStatus === FALSE) {
        $this->CartModel->rollback();
        $this->RecordModel->rollback();
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error('下单失败');
        exit;
      } else {

        $this->OrderModel->commit();
        $this->OrderProductModel->commit();
        $this->ProductModel->commit();
        $this->BusinessModel->commit();
        $this->RecordModel->commit();
        $this->CartModel->commit();
        $this->success('下单成功', '/order/index');
        exit;
      }
    }
  }

  // 单个商品购买立即下单
  /**
   * 涉及表：
   *      商品表
   *      订单表
   *      订单商品表
   *      用户表
   *      消费记录表
   */
  public function buy()
  {
    if ($this->request->isPost()) {
      $busid = $this->request->param('busid', 0, 'trim');
      $proid = $this->request->param('proid', 0, 'trim');
      $addrid = $this->request->param('addrid', 0, 'trim');
      $remark = $this->request->param('remark', '', 'trim');

      //先判断用户是否存在
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      //判断是否有商品
      $product = $this->ProductModel->where(['id' => $proid])->find();

      if (!$product) {
        $this->error('购物车记录不存在');
        exit;
      }

      $where = [
        'busid' => $busid,
        'id' => $addrid
      ];

      $address = $this->AddressModel->where($where)->find();

      if (!$address) {
        $this->error('收货地址不存在');
        exit;
      }

      //判断商品的库存是否充足
      $stock = isset($product['stock']) ? $product['stock'] : 0;
      $proname = isset($product['name']) ? $product['name'] : '';

      if ($stock <= 0) {
        $this->error("$proname 商品库存不足");
        exit;
      }

      //先判断余额是否充足
      $total = $this->ProductModel->where(['id' => $proid])->find()->value('price');

      $UpdateMoney = bcsub($business['money'], $total);

      if ($UpdateMoney < 0) {
        $this->error('余额不足');
        exit;
      }

      //开启事务
      $this->OrderModel->startTrans();
      $this->OrderProductModel->startTrans();
      $this->ProductModel->startTrans();
      $this->BusinessModel->startTrans();
      $this->RecordModel->startTrans();


      //订单表
      $OrderData = [
        'code' => build_code("FA"),
        'busid' => $busid,
        'businessaddrid' => $addrid,
        'amount' => $total,
        'remark' => $remark,
        'status' => '1',
      ];

      // 订单表
      $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);

      if ($OrderStatus === FALSE) {
        $this->error($this->OrderModel->getError());
        exit;
      }

      //订单商品表
      $OrderProductData = [];
      $ProductData = [];

      $OrderProductData[] = [
        'orderid' => $this->OrderModel->id,
        'proid' => $product['id'],
        'pronum' => 1,
        'price' => $product['price'],
        'total' => $product['price'],
      ];

      //更新商品的库存
      $stock = isset($product['stock']) ? $product['stock'] : 0;

      //更新后的库存
      $UpdateStock = bcsub($stock, 1);
      $UpdateStock = $UpdateStock <= 0 ? 0 : $UpdateStock;

      //组装数据
      $ProductData[] = [
        'id' => $product['id'],
        'stock' => $UpdateStock
      ];
    }

    // 插入订单商品表
    $OrderProductStatus = $this->OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

    if ($OrderProductStatus === FALSE) {
      $this->OrderModel->rollback();
      $this->error($this->OrderProductModel->getError());
      exit;
    }

    //更新商品库存
    $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

    if ($ProductStatus === FALSE) {
      $this->OrderProductModel->rollback();
      $this->OrderModel->rollback();
      $this->error($this->ProductModel->getError());
      exit;
    }

    //用户表更新余额
    $BusinessData = [
      'id' => $busid,
      'money' => $UpdateMoney
    ];

    $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

    if ($BusinessStatus === FALSE) {
      $this->ProductModel->rollback();
      $this->OrderProductModel->rollback();
      $this->OrderModel->rollback();
      $this->error($this->BusinessModel->getError());
      exit;
    }

    //消费记录
    $RecordData = [
      'total' => "-$total",
      'content' => "购物商品花费余额为：￥$total 元",
      'busid' => $busid
    ];

    $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

    if ($RecordStatus === FALSE) {
      $this->BusinessModel->rollback();
      $this->ProductModel->rollback();
      $this->OrderProductModel->rollback();
      $this->OrderModel->rollback();
      $this->error($this->RecordModel->getError());
      exit;
    }


    if ($OrderStatus === FALSE || $OrderProductStatus === FALSE || $ProductStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE) {
      $this->RecordModel->rollback();
      $this->BusinessModel->rollback();
      $this->ProductModel->rollback();
      $this->OrderProductModel->rollback();
      $this->OrderModel->rollback();
      $this->error('下单失败');
      exit;
    } else {

      $this->OrderModel->commit();
      $this->OrderProductModel->commit();
      $this->ProductModel->commit();
      $this->BusinessModel->commit();
      $this->RecordModel->commit();
      $this->success('下单成功', '/order/index');
      exit;
    }
  }

  // 取消订单
  /**
   * 涉及表：
   *      订单表(删除)、
   *      订单商品表(删除)
   *      商品表(更新库存)
   *      用户表(更新余额)
   *      消费记录表(插入)
   */
  public function cancel()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $orderid = $this->request->param('orderid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');

      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }


      // 开启事务
      $this->OrderModel->startTrans();
      $this->ProductModel->startTrans();
      $this->BusinessModel->startTrans();
      $this->RecordModel->startTrans();

      // 查询订单商品
      $product = $this->OrderProductModel->with(['products'])->where(['orderid' => $orderid])->select();

      $ProductData = [];
      // 遍历循环订单商品表，获取商品(数量，id)
      foreach ($product as $item) {
        // intval：转换为整型
        $pronum = intval($item['pronum']);
        $stock = isset($item['products']['stock']) ? $item['products']['stock'] : 0;
        $stock = intval($stock);

        // 商品表数据组装，
        $ProductData[] = [
          'id' => $item['proid'],
          'stock' => bcadd($stock, $pronum)
        ];
      }

      //用户余额数据组装
      $amount = $order['amount'];
      $money = $business['money'];
      $BusinessData = [
        'id' => $busid,
        'money' => bcadd($amount, $money)
      ];

      //消费记录数据组转
      $RecordData = [
        'busid' => $busid,
        'content' => "取消订单：" . $order['code'] . " ，退款金额：￥$amount",
        'total' => $amount,
      ];


      // 删除订单
      $OrderStatus = $this->OrderModel->destroy($orderid, true);
      if ($OrderStatus === FALSE) {
        $this->error('删除订单失败');
        exit;
      }


      //更新商品库存
      $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

      if ($ProductStatus === FALSE) {
        $this->OrderModel->rollback();
        $this->error('更新商品库存失败');
        exit;
      }

      //更新用户余额
      $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

      if ($BusinessStatus === FALSE) {
        $this->ProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error('更新用户余额失败');
        exit;
      }

      //消费记录
      $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

      if ($RecordStatus === FALSE) {
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error('追加消费记录失败');
        exit;
      }

      if (
        $OrderStatus === FALSE || $ProductStatus
        === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE
      ) {
        $this->RecordModel->rollback();
        $this->BusinessModel->rollback();
        $this->ProductModel->rollback();
        $this->OrderModel->rollback();
        $this->error('取消订单失败');
        exit;
      } else {
        $this->OrderModel->commit();
        $this->ProductModel->commit();
        $this->BusinessModel->commit();
        $this->RecordModel->commit();
        $this->success('取消订单成功');
        exit;
      }
    }
  }

  // 物流信息
  public function express()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {

      // 接收参数
      $orderid = $this->request->param('orderid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');

      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      // 判断订单是否发货，或 是否存在该订单
      if ($order['status'] <= '1' || empty($order['expresscode'])) {
        $this->error('订单未发货');
        exit;
      }

      // 查询物流的信息
      $express = query_express($order['expresscode']);

      // 进行判断
      if ($express) {
        $this->success('查询物流信息成功', null, $express);
        exit;
      } else {
        $this->error('物流信息查询失败');
        exit;
      }
    }
  }

  // 订单详情
  /**
   * 涉及表：
   *      订单表
   *      收货地址表
   *      物流表
   *      用户表
   *      商品表
   */
  public function info()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $orderid = $this->request->param('orderid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');

      // 查询订单信息，收货地址信息，用户信息
      $list = $this->OrderModel->with(['address', 'business'])->where(['order.busid' => $busid, 'order.id' => $orderid])->find();

      if (!$list) {
        $this->error('订单不存在');
        exit;
      }

      // 查找物流信息
      $express = query_express($list['expresscode']);
      // 取最新的一条物流信息
      if ($express) {
        $list['express'] = end($express['list']);
      } else {
        $list['express'] = '未发货，暂无物流信息';
      }

      // 查找商品表的信息
      if ($list) {
        // 查询出订单商品表去进行链表到--商品表
        $info = $this->OrderProductModel->with(['products'])->where(['orderid' => $list['id']])->select();
        $list['proData'] = $info;
      }

      if ($list) {
        $this->success('返回订单详情数据', null, $list);
        exit;
      } else {
        $this->error('暂无更多订单数据');
        exit;
      }
    }
  }

  // 确认收货
  public function receipt()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数，判断
      $orderid = $this->request->param('orderid', 0, 'trim');

      // 查询订单信息
      $list = $this->OrderModel->find($orderid);

      if (!$list) {
        $this->error('订单不存在');
        exit;
      }

      // 判断订单是否发货，或 是否存在该订单
      if ($list['status'] <= '1' || empty($list['expresscode'])) {
        $this->error('订单未发货');
        exit;
      }

      // 将订单表的状态更新为3，即已收货的状态
      $result = $this->OrderModel->where('id', $orderid)->update(['status' => '3']);

      // 判断
      if ($result) {
        $this->success('确认收货成功');
        exit;
      } else {
        $this->error('确认收货失败');
        exit;
      }
    }
  }

  // 退货退款
  public function retreat()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数，判断
      $orderid = $this->request->param('orderid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');

      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 查询订单不链表
      $Dep = $this->OrderModel->with(['address'])->find($orderid);

      if (!$Dep) {
        $this->error('订单不存在');
        exit;
      }

      $where = [
        'order.busid' => $business['id'],
        'order.id' => $orderid
      ];

      // 查询订单信息
      $list = $this->OrderModel->alias('order')->join("business_address busaddr", "order.businessaddrid = busaddr.id", "LEFT")->join("order_product ordpro", "order.id = ordpro.orderid", "LEFT")->field(['order.*', 'ordpro.*', 'busaddr.*'])->where($where)->select($orderid);

      // var_dump(collection($list)->toArray());
      // exit;

      if (!$list) {
        $this->error('订单不存在');
        exit;
      }

      // 开启事务
      $this->OrderModel->startTrans();
      $this->DepotModel->startTrans();
      $this->DepotProductModel->startTrans();

      // 将订单表的状态更新为3，即已收货的状态
      $OrderStatus = $this->OrderModel->where('id', $orderid)->update(['status' => '-3']);

      // 判断
      if ($OrderStatus === FALSE) {
        $this->error('订单更新失败');
        exit;
      }

      // 组装退货表的数据
      $DepotData = [
        'code' => build_code("ZY"),
        'ordercode' => $Dep['code'],
        'busid' => $busid,
        'contact' => $Dep['address']['consignee'],
        'phone' => $Dep['address']['mobile'],
        'address' => $Dep['address']['address'],
        'province' => $Dep['address']['province'],
        'city' => $Dep['address']['city'],
        'district' => $Dep['address']['district'],
        'amount' => $Dep['amount'],
        'expressid' => $Dep['expressid'],
        'expresscode' => $Dep['expresscode'],
        'remark' => $Dep['remark'],
        'status' => 1,
        'adminid' => $business['adminid']
      ];

      // var_dump($DepotData);o 
      // var_dump($DepotProductData);
      // exit;

      // 插入退货表中
      $DepotStatus = $this->DepotModel->validate('common/Depot/back/Back.php')->save($DepotData);

      // 判断
      if ($DepotStatus === FALSE) {
        $this->OrderModel->rollback();
        $this->error('插入退货表失败');
        exit;
      }

      $DepotProductData = [];
      // 组装退货商品表的数据
      foreach ($list as $item) {
        $DepotProductData[] = [
          'backid' => $this->DepotModel->id,
          'proid' => $item['proid'],
          'nums' => $item['pronum'],
          'price' => $item['price'],
          'total' => $item['total'],
        ];
      }

      // 插入退货商品表中
      $DepotProductStatus = $this->DepotProductModel->validate('common/Depot/back/BackProduct.php')->saveAll($DepotProductData);

      // 判断
      if ($DepotProductStatus === FALSE) {
        $this->DepotModel->rollback();
        $this->OrderModel->rollback();
        $this->error('插入退货订单表失败');
        exit;
      }

      // 如果有一个不成功
      if ($OrderStatus === FALSE || $DepotStatus === FALSE || $DepotProductStatus === FALSE) {
        $this->DepotProductModel->rollback();
        $this->DepotModel->rollback();
        $this->OrderModel->rollback();
        $this->error('退货退款失败');
        exit;
      } else {
        $this->OrderModel->commit();
        $this->DepotModel->commit();
        $this->DepotProductModel->commit();
        $this->success('退货退款成功');
        exit;
      }
    }
  }

  // 退货详情的数据
  public function retreatinfo()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $busid = $this->request->param('busid', 0, 'trim');
      $orderid = $this->request->param('orderid', 0, 'trim');

      //先判断用户是否存在
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      //先判断订单是否存在
      $order = $this->OrderModel->find($orderid);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      // 查找商品表的信息
      // 查询出订单商品表去进行链表到--商品表
      $list = $this->OrderProductModel->with(['products'])->where(['orderid' => $orderid])->select();

      // var_dump(collection($list)->toArray());
      // exit;

      if ($list) {
        $this->success('返回订单详情数据', null, $list);
        exit;
      } else {
        $this->error('暂无更多订单数据');
        exit;
      }
    }
  }

  // 商品评价中商品详情
  public function commentInfo()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $proid = $this->request->param('proid', 0, 'trim');

    // 判断用户和商品是否存在
    $business = $this->BusinessModel->find($busid);

    if (!$business) {
      $this->error('用户不存在');
      exit;
    }

    // 查询订单信息
    $orderProduct = $this->OrderProductModel->with(['products'])->find($proid);

    if (!$orderProduct) {
      $this->error('订单商品不存在');
      exit;
    }

    $order = $this->OrderModel->find($orderProduct['orderid']);

    if (!$order) {
      $this->error('订单不存在');
      exit;
    }

    $this->success('返回商品数据成功', null, $orderProduct);
  }

  // 评价
  public function comment()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数，判断
      $busid = $this->request->param('busid', 0, 'trim');
      $proid = $this->request->param('proid', 0, 'trim');
      $comment = $this->request->param('comment', 0, 'trim');

      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 查询订单信息
      $orderProduct = $this->OrderProductModel->find($proid);

      if (!$orderProduct) {
        $this->error('订单商品不存在');
        exit;
      }

      $order = $this->OrderModel->find($orderProduct['orderid']);

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      // 查询订单中的订单商品
      $ProductStatus = $this->OrderProductModel->where(['orderid' => $order['id']])->select();

      // 将当前商品评价全为false，没有评价
      $isShow = false;

      // 判断当前商品是否为全部评价
      foreach ($ProductStatus as $item) {
        // 如果商品都没有评论
        if (empty($item['comment'])) {
          // 如果评论的商品id没有全部等于当前的所有商品id，这个时候就会等于false
          if ($item['id'] != $proid) {
            $isShow = true;
          }
        }
      }

      // 如果$isShow为真，说明没有全部评论完，因为走到了for循环里面（里面在判断，当前你评论的商品，是否全都都有$item['comment']）
      if ($isShow) {
        // 有多个商品待评价
        $data = [
          'busid' => $busid,
          'comment' => $comment,
        ];

        // 更新商品订单表的评价内容
        $result = $this->OrderProductModel->where('id', $proid)->update($data);

        if (!$result) {
          $this->error('商品评价失败');
        } else {
          $this->success('商品评价成功！');
        }
      } else {
        // 单个商品评价
        // 开启事务
        $this->OrderModel->startTrans();
        $this->OrderProductModel->startTrans();

        // 更新订单表中的状态
        $OrderStatus = $this->OrderModel->where('id', $order['id'])->update(['status' => '4']);

        if ($OrderStatus === FALSE) {
          $this->error('订单操作失败');
        }

        // 组装数据，更新商品订单表的评论内容
        $OrderProductData = [
          'busid' => $busid,
          'comment' => $comment
        ];

        $OrderProductStatus = $this->OrderProductModel->where('id', $proid)->update($OrderProductData);

        if ($OrderProductStatus === FALSE) {
          // 回滚
          $this->OrderModel->rollback();
          $this->error('商品评价失败');
        }

        // 如果有一个失败
        if ($OrderProductStatus === FALSE || $OrderStatus === FALSE) {
          // 回滚
          $this->OrderProductModel->rollback();
          $this->OrderModel->rollback();
          $this->error('评价失败');
        } else {
          $this->OrderModel->commit();
          $this->OrderProductModel->commit();
          $this->success('评价成功');
        }
      }
    }
  }
}
